import {Component, ElementRef, EventEmitter, Input, OnInit, Output, ViewChild} from '@angular/core';
import {FileUploader} from 'ng2-file-upload/ng2-file-upload';
import {FileItem, FileUploaderOptions, ParsedResponseHeaders} from "ng2-file-upload";
import {InterbankService} from "../interbank.service";
import {Util} from "../../../common/util";
import {environment} from "../../../../environments/environment";

@Component({
  selector: 'interbank-file-upload',
  templateUrl: './file-upload.component.html',
  styleUrls: ['./file-upload.component.scss']
})
export class FileUploadComponent implements OnInit {

  @ViewChild('modal')
  public modal: ElementRef;

  public $modal: any;

  @ViewChild('fileInput')
  public fileInput: ElementRef;

  @ViewChild('form')
  public form: ElementRef;

  public defaultConfig: FileUploaderOptions = {
    autoUpload: false,
    url: "",
    method: 'post',
    itemAlias: 'file'
  };

  @Input()
  public config: FileUploaderOptions = {};

  public uploader: FileUploader = new FileUploader({url: ''});

  public fileSource = {
    fileName: "",
    tradeOrderFileId: "",
    orderSerialNo: ""
  };

  @Output()
  public removeFileEmitter: EventEmitter<boolean> = new EventEmitter<boolean>();

  @Output()
  public uploadFileEmitter: EventEmitter<boolean> = new EventEmitter<boolean>();

  constructor(public service: InterbankService) {
  }

  ngOnInit() {
    this.config = Util.$.extend(true, {}, this.defaultConfig, this.config);
    this.uploader.setOptions(this.config);
    this.$modal = Util.$(this.modal.nativeElement);
  }

  public toggleModalOpen() {
    return this.$modal.modal('show');
  }

  public toggleModalClose() {
    return this.$modal
      .one('hidden.bs.modal', () => {
        this.clearFileQueue();
      })
      .modal('hide');
  }

  public toggleModal() {
    this.clearFileQueue();
    return this.$modal.modal('toggle');
  }

  /**
   * 设置已上传附近列表
   * @param orderSerialNo
   * @param tradeOrderFileId
   * @param fileName
   */
  public setUploadedFileList(orderSerialNo: string = "", tradeOrderFileId: string = "", fileName: string = "") {
    if (tradeOrderFileId && tradeOrderFileId.length > 0) {
      const fileList: File[] = [];
      fileList.push(new File([], fileName));
      this.uploader.clearQueue();
      this.uploader.addToQueue(fileList);
      this.uploader.queue.forEach((item) => {
        item.isSuccess = true;
        item.isUploaded = true;
        item.progress = 100;
      });
    }
    this.setFileSource(orderSerialNo, tradeOrderFileId, fileName);
  }

  /**
   * 点击后新增文件流对象到uploader对象上传队列中
   * @param $event
   */
  public setFileOnChange($event) {
    const files: File[] = Array.prototype.slice.call($event.target.files);
    const fileName = files.length > 0 ? files[0].name : "";
    this.setFileSource(this.fileSource.orderSerialNo, "", fileName);
    this.uploader.clearQueue();
    this.uploader.addToQueue(files);
    console.log(this.uploader.queue);
  }

  /**
   * 是否允许上传附件
   * @returns {boolean}
   */
  public isCanUpload(): boolean {
    const file: FileItem = this.uploader.queue[0];
    const result: boolean = (file == null || file.isUploaded || file.isUploading) ? false : true;
    return result;
  }

  /**
   * 是否允许删除附件
   * @returns {boolean}
   */
  public isCanDelete(): boolean {
    const file: FileItem = this.uploader.queue[0];
    const result: boolean = (file != null && !file.isUploading) ? true : false;
    return result;
  }

  /**
   * 清空上传附件队列
   */
  public clearFileQueue() {
    if (this.isCanDelete()) {
      this.uploader.clearQueue();
      this.form.nativeElement.reset();
      this.setFileSource(this.fileSource.orderSerialNo, "", "");
    }
  }

  /**
   * 设置待处理文件对象信息
   * @param orderSerialNo
   * @param tradeOrderFileId
   * @param fileName
   * @returns {{fileName: string, tradeOrderFileId: string,orderSerialNo: string}}
   */
  public setFileSource(orderSerialNo: string = "", tradeOrderFileId: string = "", fileName: string = "") {
    this.uploader.options.url = new window['URI'](environment.server + this.config.url).toString() + `/${orderSerialNo}`;
    return this.fileSource = {
      fileName: fileName,
      tradeOrderFileId: tradeOrderFileId,
      orderSerialNo: orderSerialNo
    };
  }

  /**
   * 上传附件
   */
  public uploadFile() {
    if (this.isCanUpload()) {
      this.uploader.onSuccessItem = (item: FileItem, response: string, status: number, headers: ParsedResponseHeaders) => {
        try {
          const result = JSON.parse(response);
          const data = result.data;
          if (result && result.code === 0) {
            this.fileSource.tradeOrderFileId = (data != null && data.tradeOrderFileId) ? data.tradeOrderFileId : "";
            window['swal']("提示", "附件上传成功！", "success");
            this.uploadFileEmitter.emit(true);
          } else {
            window['swal']("提示", "附件上传失败！", "error");
          }
        } catch (e) {
          window['swal']("提示", "附件上传失败！", "error");
        }

      };
      // TODO 为了测试，上线要去掉
      this.uploader.queue.forEach((item) => {
        item.headers = [{name: 'token', value: sessionStorage.getItem('username')}];
      });
      this.uploader.uploadAll();
    }
  }

  /**
   * 删除附件
   */
  public removeFile() {
    const tradeOrderFileId = this.fileSource.tradeOrderFileId;
    if (tradeOrderFileId != null && tradeOrderFileId.length > 0) {
      this.service.removeFile(this.fileSource.orderSerialNo).subscribe((data) => {
        if (data != null && data.code === 0) {
          this.clearFileQueue();
          this.removeFileEmitter.emit(true);
          window["swal"]("提示", "附件删除成功！", "success");
        } else {
          window["swal"]("提示", "附件删除失败！", "error");
        }
      });
    } else {
      this.clearFileQueue();
    }
  }

  /**
   * 下载附件
   */
  public downloadFile() {
    const tradeOrderFileId = this.fileSource.tradeOrderFileId;
  }
}
